#!/usr/bin/python3
# coding:utf-8

import sys
import os
import time
from enum import IntEnum
from dataclasses import dataclass
from Sweeper_Model_Config import *


class Log_Manage:
    def __init__(self, log_config):
        self.config = log_config.log_config

    def get_and_update_logfile_index(self, file):
        if not os.path.exists(file):
            with open(file, "w") as fp:
                fp.write("1")
            return 1

        with open(file, "r+") as fp:
            buf = fp.read()
            if len(buf) == 0:
                num = 0
            else:
                num = int(buf)

            num += 1
            if num > 9999:
                num = 1
            num_str = str(num)
            fp.seek(0)
            fp.write(num_str)

        return num

    def gen_log_dir(self):
        now_time_stamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
        index_file = self.config.Log_Index_File
        idx = self.get_and_update_logfile_index(index_file)
        log_dir_name = f"{self.config.Log_Dir}/{idx:04d}_{now_time_stamp}"
        # os.mkdir(log_dir_name)
        os.makedirs(log_dir_name, exist_ok=True)
        # os.remove(self.config.Log_Symlink_Dir)
        os.system(f"rm -rf {self.config.Log_Symlink_Dir}")
        os.symlink(log_dir_name, self.config.Log_Symlink_Dir)

        return log_dir_name


class Ctrl_node:
    def __init__(self, model):
        if not self.select_match_model(model):
            print(f"匹配型号失败, 没有此型号配置: {model} ")
            sys.exit(1)

        print(f"匹配型号成功 {model}")
        self.model = self.config.Model_Name
        self.init_environ()

    def init_environ(self):
        ros_log_dir = self.config.log_config.Log_Symlink_Dir
        os.environ["ROS_LOG_DIR"] = ros_log_dir

    def run_cmd(self, cmd):
        node_list = self.config.Node_List
        os.chdir("../")
        print("new workdir:", os.getcwd())
        curdir = os.getcwd()
        # 启动命令: 则创建目录
        if cmd == "start":
            self.log_manage = Log_Manage(self.config)
            self.log_manage.gen_log_dir()

        for node in node_list:
            node_dir = node.node_dir
            if cmd == "start":
                node_cmd = node.start_cmd
            elif cmd == "stop":
                node_cmd = node.stop_cmd
            print(f"cd {node_dir}; ./{node_cmd} &")

            os.chdir(node_dir)
            os.system(f"./{node_cmd} &")
            os.chdir(curdir)

    def select_match_model(self, model):
        if model == sweeper_model_a.Model_Name:
            self.config = sweeper_model_a
        else:
            return False

        return True


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print(f"argc not right ,argc={len(sys.argv)}")
        sys.exit(1)

    model = sys.argv[1]
    cmd = sys.argv[2]
    print(f"model={model} cmd={cmd}")
    ctrl_node = Ctrl_node(model)
    ctrl_node.run_cmd(cmd)
